<?php

namespace App\controller;

use support\Redis;
use support\Request;
use think\facade\Db;
use Illuminate\Support\Env;
use app\controller\RestBase;
use think\exception\ValidateException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

class RankApi
{
    /**
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(Request $request)
    {
        $data = [
            'goods_series_id' => $request->get('goods_series_id') ?? '', // 藏品的系列id
        ];

        if (empty($data['goods_series_id'])) {
            return json(['code' => 0, 'msg' => '请传入藏品系列id']);
        }

        // 根据藏品系列 获取藏品id的集合
        $goods_ids = Db::name('goods')->where('goods_series_id', $data['goods_series_id'])->column('id');

        if (empty($goods_ids)) {
            return json(['code' => 0, 'msg' => '此藏品系列下无任何藏品']);
        }

        $prefix = env('REDIS_PREFIX');

        $key = $prefix . 'ranking:nft:list';
        $cache = Redis::get($key);

        if (!$cache) {
            $is_cache = 0;
            $list = Db::name('nft_list')
                ->where('goods_id', 'in', $goods_ids)
                ->where('is_lock', 0) // 未锁定状态的
                ->group('uid')
                ->field('uid,count(*) as count')
                ->order('count desc')
                ->limit(100)
                ->select()
                ->all();

            $user_ids = array_column($list, 'uid');
            $userList = Db::name('user')->where('id', 'in', $user_ids)->select()->all();

            foreach ($list as $k => $v) {
                for ($i = 0; $i < count($userList); $i++) {
                    if ($v['uid'] == $userList[$i]['id']) {
                        $list[$k]['userInfo'] = $userList[$i];
                    }
                }
            }

            Redis::setex($prefix . 'ranking:nft:list', 300, json_encode($list));
        } else {
            $is_cache = 1;
            $list = json_decode($cache, true);
        }


        return json(['code' => 1, 'msg' => '获取持仓排行榜成功', 'data' => $list, 'is_cache' => $is_cache]);
    }
}
